/* eslint-disable react/no-children-prop */
import React, { useContext, useEffect } from 'react';

import {
  checkEmailExist,
  clearEmailAuthError,
  clearEmailStatus,
  setEmailAuthProcess,
} from '@/entities/auth/model/actions';
import { getAuthProcessEmail, getDoesUserExist, getEmailAuthError } from '@/entities/auth/model/selectors';
import { env, innerUrls } from '@/shared/constants';
import { ModalContext } from '@/shared/context/ModalContext';
import { ReactComponent as Apple } from '@/shared/icons/logo/Apple.svg';
import { ReactComponent as Google } from '@/shared/icons/logo/Google.svg';
import { ReactComponent as VK } from '@/shared/icons/logo/VK.svg';
import { ReactComponent as Yandex } from '@/shared/icons/logo/Yandex.svg';
import { Modals } from '@/shared/interfaces';
import { validateEmail } from '@/shared/lib';
import { useKeyboard } from '@/shared/lib/hooks';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, FlexWrapper, Input, Title } from '@/shared/ui';
import { Header } from '@/widgets/Header';
import { useRouter } from 'next/router';
import { useWindowSize } from 'usehooks-ts';

import s from './Auth.module.scss';

const authChoose = Object.freeze([
  {
    logo: <Yandex />,
    value: 'yandex',
  },
  {
    logo: <VK />,
    value: 'vk',
  },
  {
    logo: <Google />,
    value: 'google',
  },
  {
    logo: <Apple />,
    value: 'apple',
  },
]);

// const AuthApiService = new AuthApi();

export const Auth = () => {
  const email = useAppSelector(getAuthProcessEmail);
  const [isCorrectEmail, setIsCorrectEmail] = React.useState<boolean>(true); // валидация емаила
  const { width } = useWindowSize();
  const [isCorrectEmailShown, setIsCorrectEmailShown] = React.useState<boolean>(false);
  const authRef = React.useRef<HTMLInputElement>(null);
  const { openModal } = useContext(ModalContext);

  const dispatch = useAppDispatch();
  const router = useRouter();

  useEffect(() => {
    authRef?.current?.focus();
  }, []);

  const doesUserExist = useAppSelector(getDoesUserExist);

  const handleSetEmail = (event: React.ChangeEvent<HTMLInputElement>) => {
    dispatch(clearEmailAuthError());
    setIsCorrectEmail(true);
    setIsCorrectEmailShown(false);
    const { value } = event.target;
    dispatch(setEmailAuthProcess(value.replace(/\s/g, '').toLowerCase()));
  };

  React.useEffect(() => {
    dispatch(clearEmailStatus());
  }, []);

  const emailValidation = React.useCallback(() => {
    const isValid = validateEmail(email);

    if (isValid !== null) {
      setIsCorrectEmail(!!isValid);
    } else {
      setIsCorrectEmail(false);
    }
  }, [email]);

  React.useEffect(() => {
    if (email.length > 0) {
      emailValidation();
    }
  }, [email]);

  const handleCheckEmailExist = (email: string) => {
    if (!isCorrectEmail) {
      return;
    }
    setIsCorrectEmailShown(false);
    if (!isCorrectEmailShown) {
      dispatch(checkEmailExist(email));
    }
  };

  React.useEffect(() => {
    if (doesUserExist !== null && doesUserExist) {
      router.push(innerUrls.auth.password);
    } else if (doesUserExist !== null && !doesUserExist) {
      router.push(innerUrls.auth.registration);
    }
  }, [doesUserExist]);

  const handleHelpRoute = () => {
    openModal(Modals.FeedbackModal);
  };

  const handleRedirectSocial = async (value: string) => {
    router.push(`${env.apiUrl}/auth/signin/oauth/${value}?state=web-site`);
  };
  useKeyboard('Enter', () => {
    if (router.asPath === innerUrls.auth.email) {
      handleCheckEmailExist(email);
    }
  });
  const emailAuthError = useAppSelector(getEmailAuthError);

  const handleClear = () => {
    setIsCorrectEmail(true);
    dispatch(setEmailAuthProcess(''));
  };

  return (
    <>
      <Header />
      <div className={s.container}>
        <div className={s.authContainer}>
          <div className={s.titleBlock}>
            <Title tag="h1">Вход или регистрация</Title>
            <p className={s.titleP}>Через социальные сети или по почте</p>
          </div>
          <div className={s.authBlocks}>
            {authChoose.map((item) => (
              <div className={s.choose} key={item.value} onClick={() => handleRedirectSocial(item.value)}>
                {item.logo}
              </div>
            ))}
          </div>
          <FlexWrapper>
            {router.asPath === '/auth' && (
              <Input
                autoFocus={email.length === 0 && width > 768}
                className={s.inp}
                data-testid="input-email"
                htmlFor="auth"
                isAuthField
                isAutoFocus
                isClose={email.length > 0}
                isEmailField
                isNotAccepted={isCorrectEmailShown && email.length !== 0}
                isNotAcceptedText="Некорректный формат"
                onBlur={() => {
                  if (!isCorrectEmail || emailAuthError !== null) {
                    setTimeout(() => {
                      setIsCorrectEmailShown(true);
                    }, 100);
                  }
                }}
                onChange={handleSetEmail}
                onClear={handleClear}
                placeholder="Email"
                value={email}
              />
            )}
          </FlexWrapper>
          <div className={s.buttonBlock}>
            <Button
              className={s.button}
              data-testid="button-continue_auth"
              disabled={isCorrectEmailShown || email.length === 0 || emailAuthError !== null}
              onClick={() => handleCheckEmailExist(email)}
              variant={ButtonVariants.Primary}
            >
              Продолжить
            </Button>
            <p className={s.approve}>
              Соглашаюсь{' '}
              <Button
                className={s.userApprove}
                data-testid="link-privacy"
                href={innerUrls.privacy}
                link
                target="_blank"
                variant={ButtonVariants.Link}
              >
                с пользовательским соглашением
              </Button>
            </p>
          </div>
        </div>
        <Button
          className={s.notAccess}
          data-testid="button-help"
          onClick={handleHelpRoute}
          variant={ButtonVariants.Link}
        >
          Не удается войти?
        </Button>
      </div>
    </>
  );
};
